import 'package:flutter/material.dart';
import '../models/exhibition.dart';
import '../services/exhibition_service.dart';
import '../utils/theme_colors.dart';

class ExhibitionDetailScreen extends StatefulWidget {
  final Exhibition exhibition;

  const ExhibitionDetailScreen({
    Key? key,
    required this.exhibition,
  }) : super(key: key);

  @override
  State<ExhibitionDetailScreen> createState() => _ExhibitionDetailScreenState();
}

class _ExhibitionDetailScreenState extends State<ExhibitionDetailScreen> {
  final ExhibitionService _exhibitionService = ExhibitionService.instance;
  late Exhibition _exhibition;
  bool _isBookmarked = false;
  bool _isBooked = false;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _exhibition = widget.exhibition;
    _isBookmarked = _exhibition.isBookmarked;
    _checkBookingStatus();
  }

  Future<void> _checkBookingStatus() async {
    try {
      final userParticipation = await _exhibitionService.getUserParticipation('current_user_id');
      final bookedExhibition = userParticipation.bookedExhibitions
          .any((id) => id == _exhibition.id);
      setState(() {
        _isBooked = bookedExhibition;
      });
    } catch (e) {
      // 处理错误
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.background,
      body: CustomScrollView(
        slivers: [
          _buildSliverAppBar(),
          SliverToBoxAdapter(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildBasicInfo(),
                _buildDescription(),
                _buildExhibitItems(),
                _buildLocationInfo(),
                _buildTimeInfo(),
                _buildPriceInfo(),
                if (_exhibition.hasVirtualTour) _buildVirtualTour(),
                const SizedBox(height: 100), // 为底部按钮留空间
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  Widget _buildSliverAppBar() {
    return SliverAppBar(
      expandedHeight: 300,
      pinned: true,
      backgroundColor: ThemeColors.primary,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
        onPressed: () => Navigator.pop(context),
      ),
      actions: [
        IconButton(
          icon: Icon(
            _isBookmarked ? Icons.bookmark : Icons.bookmark_border,
            color: Colors.white,
          ),
          onPressed: _toggleBookmark,
        ),
        IconButton(
          icon: const Icon(Icons.share, color: Colors.white),
          onPressed: _shareExhibition,
        ),
      ],
      flexibleSpace: FlexibleSpaceBar(
        background: Stack(
          fit: StackFit.expand,
          children: [
            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    ThemeColors.primary,
                    ThemeColors.secondary,
                  ],
                ),
              ),
            ),
            const Center(
              child: Icon(
                Icons.museum,
                size: 80,
                color: Colors.white,
              ),
            ),
            // 状态标签
            Positioned(
              top: 100,
              left: 20,
              child: _buildStatusBadge(),
            ),
            // VR标签
            if (_exhibition.hasVirtualTour)
              Positioned(
                top: 100,
                right: 20,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.deepOrange,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        Icons.view_in_ar,
                        size: 16,
                        color: Colors.white,
                      ),
                      SizedBox(width: 4),
                      Text(
                        'VR展厅',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusBadge() {
    Color backgroundColor;
    String text;
    
    switch (_exhibition.status) {
      case ExhibitionStatus.upcoming:
        backgroundColor = Colors.orange;
        text = '即将开展';
        break;
      case ExhibitionStatus.ongoing:
        backgroundColor = Colors.green;
        text = '正在展出';
        break;
      case ExhibitionStatus.completed:
        backgroundColor = Colors.grey;
        text = '已结束';
        break;
      case ExhibitionStatus.cancelled:
        backgroundColor = Colors.red;
        text = '已取消';
        break;
    }
    
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  Widget _buildBasicInfo() {
    return Container(
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  _exhibition.title,
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: ThemeColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Text(
                  _exhibition.type.displayName,
                  style: TextStyle(
                    fontSize: 12,
                    color: ThemeColors.primary,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Icon(
                Icons.people,
                size: 20,
                color: ThemeColors.primary,
              ),
              const SizedBox(width: 8),
              Text(
                '${_exhibition.visitCount}人参观',
                style: TextStyle(
                  fontSize: 14,
                  color: ThemeColors.textSecondary,
                ),
              ),
              const SizedBox(width: 20),
              Icon(
                Icons.star,
                size: 20,
                color: Colors.amber,
              ),
              const SizedBox(width: 4),
              Text(
                '4.8',
                style: TextStyle(
                  fontSize: 14,
                  color: ThemeColors.textSecondary,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildDescription() {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '展览介绍',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Text(
            _exhibition.description,
            style: TextStyle(
              fontSize: 14,
              color: ThemeColors.textSecondary,
              height: 1.6,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildExhibitItems() {
    if (_exhibition.items.isEmpty) {
      return const SizedBox.shrink();
    }

    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '展品介绍',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          ...(_exhibition.items.take(3).map((item) => _buildExhibitItem(item))),
          if (_exhibition.items.length > 3)
            TextButton(
              onPressed: () {
                // 显示所有展品
              },
              child: Text('查看全部${_exhibition.items.length}件展品'),
            ),
        ],
      ),
    );
  }

  Widget _buildExhibitItem(ExhibitItem item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: ThemeColors.background,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: ThemeColors.primary.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              Icons.image,
              color: ThemeColors.primary,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item.name,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  item.description,
                  style: TextStyle(
                    fontSize: 12,
                    color: ThemeColors.textSecondary,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                if (item.period.isNotEmpty)
                  Text(
                    item.period,
                    style: TextStyle(
                      fontSize: 11,
                      color: ThemeColors.primary,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLocationInfo() {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '展览地点',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Icon(
                Icons.location_on,
                color: ThemeColors.primary,
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  _exhibition.location,
                  style: const TextStyle(
                    fontSize: 14,
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  // 打开地图
                },
                child: const Text('查看地图'),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTimeInfo() {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '展览时间',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Icon(
                Icons.access_time,
                color: ThemeColors.primary,
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '${_formatDate(_exhibition.startDate)} - ${_formatDate(_exhibition.endDate)}',
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '开放时间：09:00 - 17:00',
                      style: TextStyle(
                        fontSize: 12,
                        color: ThemeColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPriceInfo() {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '门票信息',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Icon(
                Icons.local_activity,
                color: ThemeColors.primary,
              ),
              const SizedBox(width: 8),
              Text(
                _exhibition.price > 0 ? '¥${_exhibition.price}' : '免费参观',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: _exhibition.price > 0 ? ThemeColors.primary : Colors.green,
                ),
              ),
              if (_exhibition.price > 0) ...[
                const SizedBox(width: 8),
                Text(
                  '学生半价',
                  style: TextStyle(
                    fontSize: 12,
                    color: ThemeColors.textSecondary,
                  ),
                ),
              ],
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildVirtualTour() {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(20),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'VR虚拟展厅',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Colors.deepOrange.withOpacity(0.1), Colors.orange.withOpacity(0.1)],
              ),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.deepOrange.withOpacity(0.3)),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.view_in_ar,
                  size: 32,
                  color: Colors.deepOrange,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        '360°沉浸式体验',
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Text(
                        '足不出户，在线参观展览',
                        style: TextStyle(
                          fontSize: 12,
                          color: ThemeColors.textSecondary,
                        ),
                      ),
                    ],
                  ),
                ),
                ElevatedButton(
                  onPressed: () {
                    // 启动VR展厅
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.deepOrange,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20),
                    ),
                  ),
                  child: const Text(
                    '进入VR',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomBar() {
    final canBook = _exhibition.status == ExhibitionStatus.ongoing ||
        _exhibition.status == ExhibitionStatus.upcoming;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: Row(
          children: [
            // 价格信息
            Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _exhibition.price > 0 ? '¥${_exhibition.price}' : '免费',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: _exhibition.price > 0 ? ThemeColors.primary : Colors.green,
                  ),
                ),
                if (_exhibition.price > 0)
                  Text(
                    '学生半价',
                    style: TextStyle(
                      fontSize: 11,
                      color: ThemeColors.textSecondary,
                    ),
                  ),
              ],
            ),
            const SizedBox(width: 16),
            // 预约按钮
            Expanded(
              child: ElevatedButton(
                onPressed: canBook ? _handleBooking : null,
                style: ElevatedButton.styleFrom(
                  backgroundColor: canBook ? ThemeColors.primary : Colors.grey,
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: _isLoading
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        ),
                      )
                    : Text(
                        _getBookingButtonText(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _getBookingButtonText() {
    if (!(_exhibition.status == ExhibitionStatus.ongoing ||
        _exhibition.status == ExhibitionStatus.upcoming)) {
      return '展览已结束';
    }
    
    if (_isBooked) {
      return '已预约';
    }
    
    return '立即预约';
  }

  Future<void> _handleBooking() async {
    if (_isBooked) {
      _showCancelBookingDialog();
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      await _exhibitionService.bookExhibition(_exhibition.id, 'user_123', DateTime.now());
      setState(() {
        _isBooked = true;
        _isLoading = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('预约成功！'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('预约失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  void _showCancelBookingDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('取消预约'),
        content: const Text('确定要取消预约吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              Navigator.pop(context);
              await _cancelBooking();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  Future<void> _cancelBooking() async {
    setState(() {
      _isLoading = true;
    });

    try {
      await _exhibitionService.cancelBooking(_exhibition.id, 'user_123', DateTime.now());
      setState(() {
        _isBooked = false;
        _isLoading = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('已取消预约'),
        ),
      );
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('取消失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  Future<void> _toggleBookmark() async {
    try {
      if (_isBookmarked) {
        await _exhibitionService.removeBookmark(_exhibition.id, 'user_123');
      } else {
        await _exhibitionService.addBookmark(_exhibition.id, 'user_123');
      }
      
      setState(() {
        _isBookmarked = !_isBookmarked;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(_isBookmarked ? '已收藏' : '已取消收藏'),
          duration: const Duration(seconds: 1),
        ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    }
  }

  void _shareExhibition() {
    // 实现分享功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('分享功能开发中...')),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}年${date.month}月${date.day}日';
  }
}